package requestProcess;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;

import org.apache.log4j.Logger;
import org.apache.struts.action.RequestProcessor;

public class MyRequestProcess extends RequestProcessor {
	
	private Logger logger = Logger.getLogger(MyRequestProcess.class);
	
	protected boolean processPreprocess(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession(false);
		String path = request.getServletPath();
		boolean flag = false;
		if (path.indexOf("/index.jsp") > -1) {
			logger.info("The request contains /index.jsp, so we just return true");
			return true;
		}
		if (!session.isNew()) {
			logger.info(String.format("The session %s is NOT new, so we just return true", session));
			return true;
		} else {
			try {
				logger.info(String.format("The session %s is new, so we just forward to /index.jsp and return false", session));
				flag = false;
				// If session is expired , redirect user to login Page
				// We must not invalidate the session ! If it needs to be done, "User.valueBound" has already done it. session.invalidate();
				session = null;
				request.getRequestDispatcher("/index.jsp").forward(request,
						response);
			} catch (Exception e1) {
				logger.error(String.format("Error trying to forward to /index.jsp, session %s", session), e1);
				try {
					request.getRequestDispatcher("/index.jsp").forward(request,
							response);
				} catch (Exception e2) {
					logger.error(String.format("Error trying to forward to /index.jsp, session %s, for second time", session), e2);
				}
				flag = false;
			}
		}
		return flag;

	}
}
